package chapter11.exercise.test30;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class CollectionSequence implements Collection {

    private Object[] objs;

    private int size;

    public CollectionSequence() {
        objs = new Object[10];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) > -1;
    }

    @Override
    public Iterator iterator() {
        return new Iterator() {
            private int index = 0;

            public boolean hasNext() {

                return index < size;
            }

            public Object next() {
                return objs[index++];
            }
        };
    }

    @Override
    public Object[] toArray() {
        return Arrays.copyOf(objs, size);
    }

    @Override
    public Object[] toArray(Object[] a) {
        if (a == null || a.length < size) {
            return Arrays.copyOf(a, size);
        }
        System.arraycopy(objs, 0, a, 0, size);
        if (a.length > size) {
            a[size] = null;
        }
        return a;
    }

    @Override
    public boolean add(Object e) {
        if (size >= objs.length) {
            Object[] destObjs = new Object[objs.length * 2];
            System.arraycopy(objs, 0, destObjs, 0, size);
            objs = destObjs;
        }
        objs[size++] = e;
        return true;
    }

    @Override
    public boolean remove(Object o) {

        return false;
    }

    @Override
    public boolean containsAll(Collection c) {

        return false;
    }

    @Override
    public boolean addAll(Collection c) {
        if (c != null) {
            for (Object object : c) {
                add(object);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean removeAll(Collection c) {
        return false;
    }

    @Override
    public boolean retainAll(Collection c) {
        return false;
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++)
            objs[i] = null;
        size = 0;
    }

    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (objs[i] == null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(o))
                    return i;
        }
        return -1;
    }

}
